﻿using AutoMapper;
using MediatR;
using U.B.DoMain;
using U.B.ErrorCode;
using U.B.ReadApi.Command;
using U.B.ReadApi.Dto;
using U.B.Repistory;

namespace U.B.ReadApi.CommandHander
{
    public class GetRoleUserCommandHander : IRequestHandler<GetRoleUserCommand, ApiResult<List<RUDto>>>
    {
        private readonly IRepistory<User> _userRepistory;
        private readonly IRepistory<Role> _roleRepistory;
        private readonly IRepistory<UserRole> urrepistory;
        private readonly IMapper _mapper;
        public GetRoleUserCommandHander(IRepistory<User> userRepistory, IRepistory<Role> roleRepistory, IRepistory<UserRole> urrepistory, IMapper mapper)
        {
            _userRepistory = userRepistory;
            _roleRepistory = roleRepistory;
            this.urrepistory = urrepistory;
            _mapper = mapper;
        }
        /// <summary>
        /// 角色用户显示
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<List<RUDto>>> Handle(GetRoleUserCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<RUDto>> apiResult= new ApiResult<List<RUDto>>();
            var list = from a in _userRepistory.GetAll()
                       join b in urrepistory.GetAll() on a.UserId equals b.UserId
                       join c in _roleRepistory.GetAll() on b.RoleId equals c.RoleId
                       where b.RoleId == request.RoleId
                       select new RUDto
                       {
                           UserId = a.UserId,
                           UserName = a.UserName,
                           RoleId = b.RoleId,
                           RoleName = c.RoleName,
                           UserRoleId = b.UserRoleId
                       };
            apiResult.code = Renum.显示成功;
            apiResult.Message=Renum.显示成功.ToString();
            apiResult.Data = _mapper.Map<List<RUDto>>(list);
            return Task.FromResult(apiResult);
        }
    }
}
